package com.loadburn.heron.render.adapter;

import com.google.inject.Provider;
import com.loadburn.heron.bind.Request;
import com.loadburn.heron.bind.Response;
import com.loadburn.heron.render.AdditionAttributes;
import com.loadburn.heron.render.Rendering;
import com.loadburn.heron.template.TemplateLoader;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.mvel2.templates.CompiledTemplate;
import org.mvel2.templates.TemplateRuntime;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author slacrey (scstlinfeng@yahoo.com)
 *         Date: 13-12-27
 */
public class MvelRendering implements Rendering {

    private final Provider<Request<String>> requestProvider;
    private final CompiledTemplate compiledTemplate;
    private final TemplateLoader.TemplatePage templatePage;

    public MvelRendering(Provider<Request<String>> requestProvider, CompiledTemplate compiledTemplate,
                         TemplateLoader.TemplatePage templatePage) {
        this.requestProvider = requestProvider;
        this.compiledTemplate = compiledTemplate;
        this.templatePage = templatePage;
    }

    @Override
    public void render(Object bound, Response response) {

        String templateDir = templatePage.getDecorateTemplate().getTemplateSource().getTemplateDirectory();

        AdditionAttributes additionAttributes = response.getAdditionAttributes();

        Map<String, Object> attributeMap = additionAttributes.asMap();;
        if (attributeMap == null) {
            attributeMap = new HashMap<String, Object>();
        }

        attributeMap.put("contextPath", requestProvider.get().context());
        attributeMap.put("completePath", requestProvider.get().completePath());
        attributeMap.put("messageErrors", response.getErrors());

        if (compiledTemplate != null) {
            response.write(TemplateRuntime.execute(compiledTemplate, bound, new MapVariableResolverFactory(attributeMap), templateDir).toString());
        }

    }
}
